package com.superdp.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.superdp.dto.UserDTO;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.superdp.utils.RedisConstants.LOGIN_USER_KEY;
import static com.superdp.utils.RedisConstants.LOGIN_USER_TTL;

/**
 * ClassName: RefreshTokenInterceptor
 * Package: com.superdp.utils
 * Description:
 *
 * @Author: XKing
 * @Create: 2023/6/30 - 15:52
 * @Version: 1.0
 */
public class RefreshTokenInterceptor implements HandlerInterceptor {
    /**
     * 构造器注入
     */
    private StringRedisTemplate stringRedisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate){
        this.stringRedisTemplate=stringRedisTemplate;
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.从请求头中获取token
        String token = request.getHeader("authorization");
        //1.1判断是否为空
        if(StrUtil.isBlankIfStr(token)){
            //为空直接放行
            return true;
        }
        //2.根据key查询redis是否存在用户
        String key=LOGIN_USER_KEY+token;

        Map<Object, Object> UserDTOMap = stringRedisTemplate.opsForHash().entries(key);

        if(UserDTOMap==null){
            //为空直接放行
            return true;
        }
        //2.1将map转成Bean保存到ThreadLocal
        UserDTO userDTO = BeanUtil.fillBeanWithMap(UserDTOMap, new UserDTO(), false);
        UserHolder.saveUser(userDTO);
        //3.刷新token有效期
        stringRedisTemplate.expire(key,LOGIN_USER_TTL, TimeUnit.SECONDS);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        //移除用户
        UserHolder.removeUser();
    }
}
